# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
from dezero import Variable
import dezero.functions as F
"""
创建数据集
根据输入x 预测输出y 图像为直线
实现线性回归
"""
#创建数据集
np.random.seed(0)
x = np.random.rand(100,1)
y = np.random.rand(100,1) + 2*x + 5
x,y = Variable(x),Variable(y)

W = Variable(np.zeros((1,1)))
b = Variable(np.zeros(1))

def predict(x):
    """预测线性函数"""
    y = F.matmul(x,W) + b
    return y

# #MSE
# def mean_squared_error(x0,x1):
#     """使用均方误差为损失函数 E=1/N * SUM((x0-x1)**2)"""
#     diff = x0 - x1
#     return F.sum(diff**2) / len(diff)

lr = 0.1 #learning rate
epoch = 100
for i in range(epoch):
    y_pred = predict(x)
    loss = F.mean_squared_error(y,y_pred)

    W.cleargrad()
    b.cleargrad()
    #求导
    loss.backward()
    #梯度下降法 根据梯度自更新
    W.data -= lr * W.grad.data
    b.data -= lr * b.grad.data
    # print(W,b,loss)

ret = predict(x)
plt.scatter(x.data,y.data,c='lightblue')
plt.plot(x.data,ret.data,color='black')
plt.xlabel('x')
plt.ylabel('y')
plt.show()